<template>
	<view class="layer-share" v-if="shareShow" @touchmove.stop.prevent="moveHandle" :animation="animationLayer">
		<!-- :style="[{height: layerHeight+'px'}]" -->
		<view class="share-content" :animation="animationContent">
			<view class="title">
				<view></view>
				<view>分享给好友</view>
				<tui-icon :name="'shut'" :size="'26'" :color="'#8F8F8F'" @click="click"></tui-icon>
			</view>
			<view class="truth-type">
				<!-- #ifdef APP-PLUS -->
				<view class="" @click="shareWeiXin">
					<image src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/weixin-friend.png" mode=""></image>
					<text>微信好友</text>
				</view>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<button class="" open-type='share'>
					<image src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/weixin-friend.png" mode=""></image>
					<text>微信好友</text>
				</button>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<view class="" @click="pengyouquan" v-if="shareType == 'shops'">
					<image src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/weixin-quan.png" mode=""></image>
					<text>朋友圈</text>
				</view>
				<!-- #endif -->
				<view class="" @click="getShare" v-if="!isShare">
					<image src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/shareImg.png" mode=""></image>
					<text>分享海报</text>
				</view>
				<view class="" @click="saveImage" v-if="isShare">
					<image src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/save-img.png" mode=""></image>
					<text>保存本地</text>
				</view>
				<view class="" @click="copy">
					<image src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/lianjie.png" mode=""></image>
					<text>复制链接</text>
				</view>

			</view>
		</view>
		<canvas canvas-id="myCanvasShops" v-if="canvasShow" :style="[{width:windowSize.windowWidth+'px'},{height:windowSize.windowHeight-200+'px'}]"></canvas>
		<canvas canvas-id="myCanvasCheating" v-if="canvasCheatingShow" :style="[{width:windowSize.windowWidth+'px'},{height:windowSize.windowHeight+'px'}]"></canvas>
		<image :src="shareImg" v-if="isShare || !isUse" class="share-img"></image>
	</view>
</template>

<script>
	import tuiIcon from "@/components/thorUI/icon"
	import {
		promisify
	} from '@/utils/promise.util'
	export default {
		components: {
			tuiIcon
		},
		props: {
			shareShow: {
				type: Boolean,
				default: false
			},
			animationLayer: {
				type: Object,
				default: null
			},
			animationContent: {
				type: Object,
				default: null
			},
			shareType: {
				type: String,
				default: ''
			},
			shopsInfo: {
				type: Object,
				default: null
			},
			windowSize: {
				type: Object,
				default: null
			},
			cheatingInfo: {
				type: Object,
				default: null
			}

		},
		data() {
			return {
				// 分享
				isShare: false,
				shareImg: '',
				canvasShow: false,
				// 店铺分享
				shareBanner: '',
				shareQr: '',
				newShareBg: '',
				isUse: false,
				// 助力分享
				canvasCheatingShow: false,
				c_qr: '',
				c_bg: '',
				c_text: '',
				c_box: '',
				c_shopImg: '',
				c_rgbWhite: '',
			}
		},
		methods: {
			copy() {
				var shareType = this.shareType
				if (shareType == 'shops') {
					var shopsInfo = this.shopsInfo
					uni.setClipboardData({
						data: 'http://zsgzh.miandanshidai.com/#/pages/generalDetail?busId=' + shopsInfo.id,
						success: function() {
							console.log('success');
						}
					});
				}
				// 分享助力
				if (shareType == 'cheating') {
					var cheatingInfo = this.cheatingInfo
					uni.setClipboardData({
						data: 'http://zsgzh.miandanshidai.com/#/pages/cheatingDetail?orderId=' + cheatingInfo.orderId + '&payType=' +
							cheatingInfo.payType,
						success: function() {
							console.log('success');
						}
					});
				}
			},
			moveHandle() {},
			click() {
				this.isShare = false
				this.isUse = true
				this.$emit("hideShare");
			},
			// 分享到朋友圈
			pengyouquan() {
				var that = this
				var shareType = this.shareType
				// 分享商户
				if (shareType == 'shops') {
					var shopsInfo = that.shopsInfo
					uni.share({
						provider: "weixin",
						scene: "WXSenceTimeline",
						type: 2,
						imageUrl: 'https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/resources/To-the-home-page.png',
						href: 'https://zsgzh.miandanshidai.com/#/pages/generalDetail?busId='+shopsInfo.id,
						success: function(res) {
							console.log("success:" + JSON.stringify(res));
						},
						fail: function(err) {
							console.log("fail:" + JSON.stringify(err));
						}
					});
				}
			},
			// 分享到微信
			shareWeiXin() {
				var that = this
				var shareType = this.shareType
				// 分享商户
				if (shareType == 'shops') {
					var shopsInfo = that.shopsInfo
					uni.share({
						provider: "weixin",
						type: 5,
						scene: 'WXSceneSession',
						imageUrl: 'https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/resources/shop-share-image.png',
						summary: shopsInfo.name,
						title: shopsInfo.name,
						miniProgram: {
							id: 'gh_6600608d192b',
							path: 'pages/generalDetail?busId='+shopsInfo.id,
							type: 0,
							webUrl: 'https://zsgzh.miandanshidai.com/#/pages/generalDetail?busId='+shopsInfo.id
						},
						success: function(res) {
							if (res.errMsg == 'share:ok') {
								uni.showToast({
									title: '分享成功'
								})
							}
						},
						fail: function(err) {
							uni.showToast({
								title: '分享失败'
							})
						}
					});
				}
				// 分享助力
				if (shareType == 'cheating') {
					var cheatingInfo = that.cheatingInfo
					uni.share({
						provider: "weixin",
						type: 5,
						scene: 'WXSceneSession',
						imageUrl: "https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/share-cheatig.png",
						title: '帮我助力赢好礼',
						miniProgram: {
							id: 'gh_6600608d192b',
							path: 'pages/cheatingDetail?orderId=' + cheatingInfo.orderId + '&payType=' + cheatingInfo.payType,
							type: 0,
							webUrl: 'https://zsgzh.miandanshidai.com/#/pages/cheatingDetail?orderId=' + cheatingInfo.orderId + '&payType=' + cheatingInfo.payType
						},
						success: function(res) {
							if (res.errMsg == 'share:ok') {
								uni.showToast({
									title: '分享成功'
								})
							}
						},
						fail: function(err) {
							console.log("fail11:" + JSON.stringify(err));
							uni.showToast({
								title: '分享失败'
							})
						}
					});
				}
			},
			getShare() {
				var that = this
				var shareType = this.shareType
				// 分享商户
				if (shareType == 'shops') {
					var shopsInfo = that.shopsInfo
					that.newImg(shopsInfo)
				}
				// 分享助力
				if (shareType == 'cheating') {
					var shopsInfo = that.shopsInfo
					that.newCheatingImg(shopsInfo)
				}
				// 分享商品
			},
			saveImage: function(e) {
				var that = this;
				uni.showLoading({
					title: '保存中',
				})
				uni.saveImageToPhotosAlbum({
					filePath: that.shareImg,
					success: function(res) {
						uni.hideLoading()
						uni.showToast({
							title: '保存成功',
							icon: 'success',
							duration: 3000
						})
					},
					fail: function(res) {
						uni.showToast({
							title: '保存失败',
							icon: 'error',
							duration: 300
						})
					}
				})
			},
			// 助力海报
			newCheatingImg() {
				var that = this;
				var shopsInfo = that.shopsInfo
				if (that.shareImg != '') {
					that.isShare = true
					that.isUse = false
					return
				}

				if (!shopsInfo.help_mode_qr || !shopsInfo.shop_image) {
					uni.showToast({
						title: '素材不全，请登录后台补全',
						icon: 'none'
					})
					return
				}
				that.canvasCheatingShow = false
				that.isShare = true
				that.isUse = false
				uni.showLoading({
					title: '生成海报中',
				})
				// 生成海报
				const uNiDownloadFile = promisify(uni.getImageInfo)
				Promise.all([
					uNiDownloadFile({
						src: shopsInfo.help_mode_qr
					}),
					uNiDownloadFile({
						src: 'https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/c_new_bg_new.png'
					}),
					uNiDownloadFile({
						src: 'https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/c_new_text2.png'
					}),
					uNiDownloadFile({
						src: 'https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/c_new_box_new.png'
					}),
					uNiDownloadFile({
						src: shopsInfo.shop_image
					}),
					uNiDownloadFile({
						src: 'https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/rgbaWhite.png'
					}),
				]).then(res => {
					that.c_qr = res[0].path
					that.c_bg = res[1].path
					that.c_text = res[2].path
					that.c_box = res[3].path
					that.c_shopImg = res[4].path
					that.c_rgbWhite = res[5].path
					that.drawCheatingCanvas()
				}).catch(function() {
					uni.hideLoading()
					uni.showToast({
						title: '生成海报失败',
						icon: 'none'
					});
				})
			},
			newImg(shopsInfo) {
				var that = this;
				if (that.shareImg != '') {
					that.isShare = true
					that.isUse = false
					return
				}
				that.canvasShow = false
				that.isShare = true
				that.isUse = false
				uni.showLoading({
					title: '生成海报中',
				})
				// 生成海报
				const uNiDownloadFile = promisify(uni.getImageInfo)
				Promise.all([
					uNiDownloadFile({
						src: shopsInfo.shop_image && shopsInfo.shop_image != '' ? (shopsInfo.shop_image.split(
							'//')[0] == 'http:' ? shopsInfo.shop_image.replace('http', 'https') : shopsInfo.shop_image) : 'https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/huibaigou/moren.png'
					}),
					uNiDownloadFile({
						src: shopsInfo.shop_qr_code
					}),
					uNiDownloadFile({
						src: "https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/newShare2.png"
					}),
				]).then(res => {
					that.shareBanner = res[0].path
					that.shareQr = res[1].path
					that.newShareBg = res[2].path
					that.drawCanvas()
				}).catch(function() {
					uni.hideLoading()
					uni.showToast({
						title: '生成海报失败',
						icon: 'none'
					});
				})
			},
			//适配不同屏幕大小的canvas
			setCanvasSize: function() {
				var that = this;
				var size = {};
				try {
					var res = uni.getSystemInfoSync();
					var width = res.windowWidth
					var height = res.windowHeight - 200
					size.w = width
					size.h = height
				} catch (e) {
					// Do something when catch error
					throw new Error(e)
				}
				return size
			},
			//适配不同屏幕大小的canvas
			setCanvasSizeCheating: function() {
				var that = this;
				var size = {};
				try {
					var res = uni.getSystemInfoSync();
					var width = res.windowWidth
					var height = res.windowHeight
					size.w = width
					size.h = height
				} catch (e) {
					// Do something when catch error
					throw new Error(e)
				}
				return size
			},
			// 助力海报
			drawCheatingCanvas() {
				var that = this;
				const ctx = uni.createCanvasContext('myCanvasCheating', that);
				var size = this.setCanvasSizeCheating();
				that.canvasCheatingShow = true
				ctx.drawImage(that.c_bg, 0, 0, size.w, size.h);
				ctx.drawImage(that.c_text, 0, size.h * 0.07, size.w, size.h * 0.19);
				ctx.drawImage(that.c_box, size.w * 0.05, size.h * 0.25, size.w * 0.9, size.h * 0.73);
				ctx.drawImage(that.c_qr, size.w * 0.3, size.h * 0.33, size.w * 0.4, size.w * 0.4);
				ctx.drawImage(that.c_shopImg, size.w * 0.19, size.h * 0.73, size.w * 0.65, size.h * 0.18);
				ctx.drawImage(that.c_rgbWhite, size.w * 0.19, size.h * 0.91 - 20, size.w * 0.65, 20);
				var textName = that.shopsInfo.name.length > 11 ? that.shopsInfo.name.slice(0, 11) + '...' : that.shopsInfo.name
				ctx.font = "normal 12px 微软雅黑 ";
				ctx.setFillStyle('#333333');
				var left = (size.w - ctx.measureText(textName).width) / 2;
				ctx.fillText(textName, left, size.h * 0.91 - 5);
				ctx.draw(true, () => {
					setTimeout(function() {
						uni.canvasToTempFilePath({
							canvasId: 'myCanvasCheating',
							success: function(res) {
								that.canvasCheatingShow = false
								that.shareImg = res.tempFilePath
							},
							fail(e) {
								console.log(e)
								uni.showToast({
									title: '生成海报失败',
									icon: 'none'
								});
							}
						}, that)
					}, 100)
				})
				uni.hideLoading()
			},
			// 商铺海报
			drawCanvas() {
				var that = this;
				const ctx = uni.createCanvasContext('myCanvasShops', that);
				var size = this.setCanvasSize();
				that.canvasShow = true
				const grd = ctx.createLinearGradient(0, 0, size.w, size.h);
				grd.addColorStop(0, '#ffffff');
				grd.addColorStop(1, '#ffffff');
				// Fill with gradient
				ctx.setFillStyle(grd); //将渐变色渲染入正方形
				ctx.fillRect(0, 0, size.w, size.h); //起点坐标为（20，20），长宽都为120px的正方形
				// shopBanner
				ctx.drawImage(that.shareBanner, size.w * 0.05, size.h * 0.05, size.w * 0.9, size.w * 0.75);
				ctx.drawImage(that.newShareBg, size.w * 0.03, size.h * 0.03, size.w * 0.94, size.w * 0.8)
				// 店铺名称
				var textName = that.shopsInfo.name;
				var nameRow = that.setText(ctx, textName, "normal bold 15px 微软雅黑 ", '#333')
				textName = nameRow.length > 1 ? nameRow[0] + '...' : nameRow[0];
				ctx.fillText(textName, size.w * 0.1, size.h * 0.70);
				//地址
				ctx.font = "normal normal 14px 微软雅黑 ";
				ctx.setFillStyle('#333');
				var textText = that.shopsInfo.address;
				let arrText = textText.split('');
				let line = '';
				let arrTr = [];
				for (let i = 0; i < arrText.length; i++) {
					var testLine = line + arrText[i];
					var metrics = ctx.measureText(testLine);
					var width = metrics.width;
					if (width > size.w * 0.5 && i > 0) {
						arrTr.push(line);
						line = arrText[i];
					} else {
						line = testLine;
					}
					if (i == arrText.length - 1) {
						arrTr.push(line);
					}
				}
				if (arrTr.length > 2) {
					arrTr[1] = arrTr[1] + '...'
					arrTr = arrTr.splice(0, 2)
				}
				for (let i = 0; i < arrTr.length; i++) {
					ctx.fillText(arrTr[i], size.w * 0.1, size.h * .8 + i * size.h * .05);
				}
				// 联系电话
				ctx.fillText('商铺Tel：' + that.shopsInfo.phone, size.w * 0.1, size.h * .92);
				// 二维码
				ctx.drawImage(that.shareQr, size.w * 0.68, size.h * 0.68, size.w * 0.18, size.w * 0.18);
				// 长按识别二维码
				ctx.font = "normal normal 12px 微软雅黑 ";
				ctx.setFillStyle('#ccc');
				ctx.fillText('长按识别二维码', size.w * 0.66, size.h * .88);
				ctx.fillText('分享来自  掌商APP', size.w * 0.66, size.h * .92);
				ctx.draw(true, () => {
					setTimeout(function() {
						uni.canvasToTempFilePath({
							canvasId: 'myCanvasShops',
							success: function(res) {
								that.canvasShow = false
								that.shareImg = res.tempFilePath
							},
							fail(e) {
								console.log(e)
								uni.showToast({
									title: '生成海报失败',
									icon: 'none'
								});
							}
						}, that)
					}, 100)
				})
				uni.hideLoading()
			},
			// 单行文本设置
			setText(ctx, textText, font, color) {
				var size = this.setCanvasSize();
				var chr = textText.split(""); //这个方法是将一个字符串分割成字符串数组
				var temp = "";
				var row = [];
				ctx.font = font;
				ctx.setFillStyle(color);
				for (var a = 0; a < chr.length; a++) {
					if (ctx.measureText(temp).width < size.w * 0.45) {
						temp += chr[a];
					} else {
						a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
						row.push(temp);
						temp = "";
					}
				}
				row.push(temp);
				return row
			},
		},
	}
</script>

<style scoped>
	.layer-share {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, .4);
		z-index: 1026;
		opacity: 0
	}

	.share-content {
		width: 100%;
		height: 270rpx;
		position: absolute;
		bottom: -270rpx;
		left: 0;
		border-radius: 16rpx 16rpx 0 0;
		background: #fff;
		display: flex;
		flex-direction: column;
	}

	.title {
		width: 100%;
		height: 70rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-right: 10rpx;
		box-sizing: border-box;
	}

	.title>view:nth-child(1),
	.title>view:nth-child(3) {
		width: 80rpx;

	}

	.title>view:nth-child(2) {
		flex: 1;
		color: #8f8f8f;
		text-align: center;
		font-size: 30rpx;
	}

	.truth-type {
		flex: 1;
		width: 100%;
		display: flex;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		justify-content: space-between;
	}

	.truth-type button {
		flex: 1;
		display: flex;
		flex-direction: column;
		background: #fff !important;
		align-items: center;
		padding: 0 !important;
	}

	.truth-type .button-hover {
		background: #fff !important;
	}

	.truth-type button image {
		width: 88rpx;
		height: 88rpx;
	}

	.truth-type>button>text {
		width: 100%;
		text-align: center;
		line-height: 60rpx;
		color: #333;
		font-size: 28rpx;
	}

	.truth-type>view {
		flex: 1;
		display: flex;
		flex-direction: column;

		align-items: center;
	}

	.truth-type>view>image {
		width: 88rpx;
		height: 88rpx;
	}

	.truth-type>view>text {
		width: 100%;
		text-align: center;
		line-height: 60rpx;
		color: #333;
		font-size: 28rpx;
	}

	canvas {
		position: absolute;
		top: -999999rpx;
		/* top: 0; */
		left: 0;
	}

	.share-img {
		display: block;
		overflow: hidden;
		width: 375rpx;
		height: 667rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-187rpx, -333rpx);
		z-index: 1027;
		border-radius: 8rpx;
	}
</style>
